<template>
  <el-dialog
    v-model="visible"
    title="监测数据查看"
    width="70%"
    :close-on-click-modal="false"
    :draggable="false"
    custom-class="displacementchart"
  >
    <!-- 上方监测点基本信息（最新数据） -->
    <el-card shadow="hover" class="mb-4">
      <el-descriptions title="监测点基本信息" column="2" border>
        <el-descriptions-item label="编号">{{ latest?.data_id }}</el-descriptions-item>
        <el-descriptions-item label="最新时间">{{ latest?.timestamp }}</el-descriptions-item>
        <el-descriptions-item label="X">{{ latest?.x }}</el-descriptions-item>
        <el-descriptions-item label="Y">{{ latest?.y }}</el-descriptions-item>
        <el-descriptions-item label="Z">{{ latest?.z }}</el-descriptions-item>
        <el-descriptions-item label="质量标志">{{ latest?.quality_flag }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 时间区间选择器 + 快捷按钮 -->
    <el-card shadow="never" class="mb-4">
      <el-form inline label-width="80px">
        <el-form-item label="时间区间">
          <el-date-picker
            v-model="timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 400px;"
          />
        </el-form-item>

        <el-form-item>
          <el-button size="small" @click="setQuickRange(7)">最近7天</el-button>
          <el-button size="small" @click="setQuickRange(30)">最近30天</el-button>
          <el-button size="small" @click="resetRange">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 下方折线图 -->
    <div ref="chartRef" style="height:400px;width:100%;"></div>

    <template #footer>
      <el-button @click="visible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, nextTick, computed } from "vue";
import axios from "axios";
import * as echarts from "echarts";

const visible = ref(false);
const records = ref([]);         // 全部数据（已排序）
const latest = ref(null);        // 最新数据
const timeRange = ref(null);     // 时间区间选择
const chartRef = ref(null);
let chartInstance = null;

// 计算过滤后的数据
const filteredRecords = computed(() => {
  if (!timeRange.value || timeRange.value.length < 2) {
    return records.value;
  }
  const [start, end] = timeRange.value.map((t) => new Date(t));
  return records.value.filter((item) => {
    const ts = new Date(item.timestamp);
    return ts >= start && ts <= end;
  });
});

// 打开对话框并加载数据
const open = async (pointId) => {
  visible.value = true;
  try {
    const response = await axios.get(`/monitoring-data/${pointId}/`);
    const data = response.data || [];

    if (data.length > 0) {
      // 按时间升序排序
      const sorted = [...data].sort(
        (a, b) => new Date(a.timestamp) - new Date(b.timestamp)
      );
      records.value = sorted;
      latest.value = sorted[sorted.length - 1];
    } else {
      records.value = [];
      latest.value = null;
    }

    // 默认时间区间：显示全部
    timeRange.value = null;

    // 渲染图表
    nextTick(() => {
      renderChart();
    });
  } catch (error) {
    console.error("获取监测点数据时出错:", error);
    records.value = [];
    latest.value = null;
  }
};

// 渲染 ECharts 折线图
const renderChart = () => {
  if (!chartRef.value) return;
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value);
  }

  const option = {
    title: { text: "加速度变化曲线" },
    tooltip: { trigger: "axis" },
    xAxis: {
      type: "category",
      data: filteredRecords.value.map((item) => item.timestamp),
      name: "时间",
    },
    yAxis: {
      type: "value",
      name: "加速度",
    },
    series: [
      {
        data: filteredRecords.value.map((item) => item.vector),
        type: "line",
        smooth: true,
        symbol: "circle",
      },
    ],
  };

  chartInstance.setOption(option);
};

// 设置快捷时间区间
const setQuickRange = (days) => {
  if (!records.value.length) return;
  const end = new Date(latest.value.timestamp);
  const start = new Date(end);
  start.setDate(start.getDate() - days + 1); // 往前推 N 天

  // 格式化成选择器能识别的字符串
  const format = (d) => {
    const pad = (n) => (n < 10 ? "0" + n : n);
    return (
      d.getFullYear() +
      "-" +
      pad(d.getMonth() + 1) +
      "-" +
      pad(d.getDate()) +
      " " +
      pad(d.getHours()) +
      ":" +
      pad(d.getMinutes()) +
      ":" +
      pad(d.getSeconds())
    );
  };

  timeRange.value = [format(start), format(end)];
};

// 重置时间区间（显示全部）
const resetRange = () => {
  timeRange.value = null;
};

// 当过滤条件变化时，更新图表
watch(filteredRecords, () => {
  renderChart();
});

// 当对话框关闭时销毁图表实例，避免内存泄漏
watch(visible, (val) => {
  if (!val && chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
});

defineExpose({ open });
</script>

<style scoped>
.displacementchart {
  height: 75%;
  display: flex;
  flex-direction: column;
}
.displacementchart .el-dialog__body {
  flex: 1;
  overflow-y: auto;
}
.mb-4 {
  margin-bottom: 16px;
}
</style>
